package com.engine4cloud.tdf.supervision.service.impl;

import com.engine4cloud.tdf.admin.api.dto.AreaQueryDTO;
import com.engine4cloud.tdf.admin.api.feign.RemoteAreaService;
import com.engine4cloud.tdf.admin.api.vo.AreaResultVO;
import com.engine4cloud.tdf.common.core.constant.SecurityConstants;
import com.engine4cloud.tdf.common.core.exception.ValidateCodeException;
import com.engine4cloud.tdf.common.core.util.RetOps;
import com.engine4cloud.tdf.supervision.dto.query.JzdxAreaQueryDTO;
import com.engine4cloud.tdf.supervision.dto.result.JzdxAreaResultDTO;
import com.engine4cloud.tdf.supervision.service.JzdxAreaService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class JzdxAreaServiceImpl implements JzdxAreaService {
    @Resource
    private RemoteAreaService remoteAreaService;

    @Override
    public JzdxAreaResultDTO getArea(JzdxAreaQueryDTO dto) {
        JzdxAreaResultDTO areaResult = new JzdxAreaResultDTO();

        AreaResultVO province = RetOps.of(remoteAreaService.getAreaDetail(new AreaQueryDTO(dto.getProvinceCode()), SecurityConstants.FROM_IN))
                .getData().orElseThrow(() -> new ValidateCodeException("行政区划信息 '省编码' 错误!"));

        AreaResultVO city = RetOps.of(remoteAreaService.getAreaDetail(new AreaQueryDTO(dto.getCityCode()), SecurityConstants.FROM_IN))
                .getData().orElseThrow(() -> new ValidateCodeException("行政区划信息 '市编码' 错误!"));

        areaResult.setProvince(province);
        areaResult.setCity(city);

        if (StringUtils.isNotEmpty(dto.getCountyCode())) {
            AreaResultVO county = RetOps.of(remoteAreaService.getAreaDetail(new AreaQueryDTO(dto.getCountyCode()), SecurityConstants.FROM_IN))
                    .getData().orElse(null);

            if (Objects.isNull(county)) {
                county = RetOps.of(remoteAreaService.getAreaDetail(new AreaQueryDTO(dto.getCityCode(), Long.parseLong(dto.getCountyCode())), SecurityConstants.FROM_IN))
                        .getData().orElseThrow(() -> new ValidateCodeException("行政区划信息 '区县编码' 错误!"));
            }

            areaResult.setCounty(county);

            if (Objects.nonNull(dto.getVillageAreaId())) {
                AreaResultVO village = RetOps.of(remoteAreaService.getAreaDetail(new AreaQueryDTO(dto.getCountyCode(), dto.getVillageAreaId()), SecurityConstants.FROM_IN))
                        .getData().orElseThrow(() -> new ValidateCodeException("行政区划信息 '乡镇区域id' 错误!"));

                areaResult.setVillage(village);
            }

        }

        return areaResult;
    }
}